package com.wowangz.cms.syscore;

import java.io.IOException;
import java.io.Reader;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.wowangz.cms.common.utils.DataDictionaryManage;
import com.wowangz.cms.syscore.utils.LoadBaseDataConstants;
import com.wowangz.cms.syscore.utils.RedisConfig;
import com.wowangz.cms.syscore.utils.SpringUtil;
import com.wowangz.cms.systemmanage.passwordpolicy.pojo.PasswordPolicy;

@SuppressWarnings({ "serial", "rawtypes", "unchecked" })
public class InitEnvironment extends HttpServlet {
	private static Map<String, List<Object>> baseDataCacheMap = new HashMap<String, List<Object>>();

	private static SqlSessionFactory sqlSessionFactory;

	public static Map<String, List<Object>> getBaseDataCacheMap() {
		return baseDataCacheMap;
	}

	/**
	 * @描述 获得密码规则
	 * @author HUANGYUAN 2015年8月12日 下午2:41:45
	 *
	 * @param sqlsession
	 * @return
	 */
	public static List<Object> getPasswordPolicy(SqlSession sqlsession) {
		List<Object> maps = new ArrayList<Object>();
		Map<String, Object> passwordMap = new HashMap<String, Object>();
		List<PasswordPolicy> selectList = sqlsession.selectList("PasswordPolicy.queryPasswordPolicyList");
		for (PasswordPolicy passwordPolicy : selectList) {
			passwordMap.put(passwordPolicy.getCode(), passwordPolicy.getValue());
		}
		maps.add(passwordMap);
		return maps;
	}

	public static SqlSessionFactory getSqlSessionFactory() {
		return sqlSessionFactory;
	}

	// 加载基础数据，缓存到map中
	public static void loadBaseData() {
		SqlSession sqlsession = null;
		try {
			DriverManagerDataSource dataSource = (DriverManagerDataSource) SpringUtil.getBean("publicDataSource");
			sqlsession = InitEnvironment.getSqlSessionFactory().openSession(dataSource, true);
			// 加载币种数据
			List currencyList = sqlsession.selectList("Currency.queryCurrency");
			// 加载大行数据
			List headBankList = sqlsession.selectList("HeadBank.queryHeadBank");
			baseDataCacheMap.put(LoadBaseDataConstants.BASE_DATA_CURR, currencyList);
			baseDataCacheMap.put(LoadBaseDataConstants.BASE_DATA_HEADBANK, headBankList);
			baseDataCacheMap.put(LoadBaseDataConstants.PASSWORDPOLICY, getPasswordPolicy(sqlsession));

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (sqlsession != null) {
				sqlsession.close();
			}
		}

	}

	/**
	 * 缓存map重新加载数据
	 *
	 * @param reloadKey
	 */
	public static void reloadBaseDate(String reloadKey) {
		SqlSession sqlsession = null;
		try {
			DriverManagerDataSource dataSource = (DriverManagerDataSource) SpringUtil.getBean("publicDataSource");
			sqlsession = InitEnvironment.getSqlSessionFactory().openSession(dataSource, true);
			if (LoadBaseDataConstants.BASE_DATA_CURR.equals(reloadKey)) {
				// 加载币种数据
				List currencyList = sqlsession.selectList("Currency.queryCurrency");
				baseDataCacheMap.put(LoadBaseDataConstants.BASE_DATA_CURR, currencyList);
				baseDataCacheMap.put(LoadBaseDataConstants.PASSWORDPOLICY, getPasswordPolicy(sqlsession));
			} else if (LoadBaseDataConstants.BASE_DATA_HEADBANK.equals(reloadKey)) {
				// 加载大行数据
				List headBankList = sqlsession.selectList("HeadBank.queryHeadBank");
				baseDataCacheMap.put(LoadBaseDataConstants.BASE_DATA_HEADBANK, headBankList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (sqlsession != null) {
				sqlsession.close();
			}
		}

	}

	public static void setBaseDataCacheMap(Map<String, List<Object>> baseDataCacheMap) {
		InitEnvironment.baseDataCacheMap = baseDataCacheMap;
	}

	public static void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		InitEnvironment.sqlSessionFactory = sqlSessionFactory;
	}

	public InitEnvironment() {
	}

	@Override
	public void init() throws ServletException {
		super.init();

		// 加载环境上下文
		WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
		
		initEnv(ctx);

		// 读取redis配置信息xml
		RedisConfig.getRedisGroupMap();
		// 查询服务器基础数据，加载到本地缓存中
		loadBaseData();
		// 缓存数据字典
		DataDictionaryManage.initDataDictionary();

	}
	
	
	private static void initEnv(WebApplicationContext ctx)
	{
		SpringUtil.applicationContext = ctx;
		// 读取mybatis配置文件
		Reader reader = null;
		try {
			reader = Resources.getResourceAsReader("mybatis.xml");
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
    public void destroy() {
        super.destroy();
        try{
            DriverManager.deregisterDriver(DriverManager.getDrivers().nextElement());
        }catch(Exception e){
            e.printStackTrace();
        }
    }
	
	
}
